<template>
  <div class="container">
    <star-nav-bar title="我的资料" style="background: var(--gray-background)" />
    <div class="profile-content">
      <div class="avatar">
        <img :src="avatarUrl" alt="头像" />
        <van-uploader
          action="/api/common/upload"
          :before-read="beforeRead"
          :after-read="afterRead"
          :max-size="500 * 1024"
          @oversize="onOversize"
          :max-count="1"
        >
          <div>
            <van-icon name="photograph" />
            <span style="padding-left: 3px"> 更换 </span>
          </div>
        </van-uploader>
      </div>
      <div class="profile">
        <div class="box item" @click="showNamePopup = true">
          <span class="value">昵称</span>
          <span>{{ userInfo.name }} <van-icon name="arrow" /></span>
        </div>
        <div class="box item" @click="showSexPopup = true">
          <span class="value">性别</span>
          <span>{{ userInfo.sex === '1' ? '男' : '女' }} <van-icon name="arrow" /></span>
        </div>
      </div>
      <!-- 修改昵称弹窗 -->
      <van-popup v-model:show="showNamePopup" round>
        <div style="text-align: center">修改昵称</div>
        <van-field v-model="checkedName" placeholder="请输入昵称"
          ><template #button>
            <van-button size="small" type="primary" @click="nameHandle">确认</van-button>
          </template>
        </van-field>
      </van-popup>
      <!-- 修改性别弹窗 -->
      <van-popup v-model:show="showSexPopup" round>
        <van-radio-group v-model="checkedSex" @click="sexHandle">
          <van-cell-group inset>
            <van-cell title="男" clickable>
              <template #right-icon>
                <van-radio name="1" />
              </template>
            </van-cell>
            <van-cell title="女" clickable>
              <template #right-icon>
                <van-radio name="0" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </van-popup>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getUserAPI, putAvatarAPI, putUserAPI } from '@/api/user'
import { useUserStore } from '@/stores'
import type { UserResult } from '@/types/user'
import { ref, onMounted } from 'vue'
import {
  showFailToast,
  showSuccessToast,
  type UploaderAfterRead,
  type UploaderBeforeRead,
  type UploaderFileListItem,
} from 'vant'
// 用户store
const userStore = useUserStore()
const user = userStore.user
const userInfo = ref({} as UserResult)
const avatarUrl = ref('')
// 修改昵称弹窗
const showNamePopup = ref(false)
const checkedName = ref('')
// 修改性别弹窗
const showSexPopup = ref(false)
const checkedSex = ref('1')
// 获取个人信息
const getUserInfo = async () => {
  try {
    const { data } = await getUserAPI(user.id)
    // 更新整个userInfo对象
    userInfo.value = data
    avatarUrl.value = data.avatar
    checkedSex.value = data.sex
    checkedName.value = data.name
  } catch (error) {
    console.log(error)
  }
}
// 修改头像
// 限制上传图片大小
const onOversize = () => {
  showFailToast('文件大小不能超过 500kb')
}
// 上传前置处理图片格式
const beforeRead: UploaderBeforeRead = (file) => {
  if (!/image\/\w+/.test((file as File).type)) {
    showFailToast('请上传图片格式的文件')
    return false
  }
  return true
}
// 上传图片
const afterRead: UploaderAfterRead = async (file) => {
  // 创建 FormData 对象准备上传文件
  const formData = new FormData()
  formData.append('file', (file as UploaderFileListItem).file as File)
  try {
    const response = await fetch('/api/common/upload', {
      method: 'POST',
      body: formData,
    })
    const data = await response.json()

    if (data.code === 1) {
      await putAvatarAPI({ id: user.id, avatar: data.data })
      getUserInfo()
      showSuccessToast('上传成功')
    } else {
      showFailToast('上传失败，请稍后再试')
    }
  } catch (error) {
    console.log(error)
    showFailToast('上传过程中出现错误，请检查网络或稍后再试')
  }
}
// 修改昵称
const nameHandle = async () => {
  try {
    await putUserAPI({ id: userInfo.value.id, name: checkedName.value })
    showNamePopup.value = false
    getUserInfo()
  } catch (error) {
    console.log(error)
  }
}
// 修改性别
const sexHandle = async () => {
  const params = {
    id: userInfo.value.id,
    sex: checkedSex.value,
  }
  try {
    await putUserAPI(params)
    showSexPopup.value = false
    getUserInfo()
  } catch (error) {
    console.log(error)
  }
}
onMounted(() => {
  getUserInfo()
})
</script>
<style scoped lang="scss">
:deep() {
  .van-uploader__wrapper {
    justify-content: space-evenly;
    align-items: center;
  }
}
.avatar {
  padding-top: 26px;
  padding-bottom: 20px;
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    height: 80px;
    width: 80px;
    object-fit: cover;
    border-radius: 50%;
    overflow: hidden;
  }
}
.van-uploader {
  width: 50px;
  height: 20px;
  line-height: 20px;
  position: absolute;
  bottom: 0px;
  font-size: 12px;
  background: #fff;
  border-radius: 5px;
}

.profile {
  margin: 20px 0;
  .item {
    padding: 0 10px;
    margin-bottom: 15px;
    min-height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.van-popup {
  min-width: 300px;
  min-height: 100px;
  padding: 10px;
}
</style>
